const redis = require("../../../../redis/init.js");
const constant = require("../../../../constant/index.js");
const userCanelLikes = async (req, res) => {
  const { article_id,user_id } = req.body;
  //用户点赞文章的集合的set
  const userLikedArticlesSetKey = `${constant.USER_LIKED_ARTICLES(user_id)}`;
  //用户点赞单个文章的set
  const userLikesSetKey = `${constant.USER_IS_READY_LIKE(user_id, article_id)}`;
  //用于映射到整个文章列表的key
  const articleLikesKey = `${constant.ART_LIKE(article_id)}`;
  //删除用户点赞的该文章的set
  await redis.sRem(userLikesSetKey, user_id+'');
  await redis.sRem(userLikedArticlesSetKey,article_id+'');//删除用户点赞集合中的文章id
  await redis.hIncrBy(articleLikesKey, "count", -1);//点赞数减一
  const likeCount = await redis.hGet(articleLikesKey,"count")//获取点赞数
    await redis.lRange("articlesList", 0, -1).then(async (list) => {
      for (let i = 0; i < list.length; i++) {
        const article = JSON.parse(list[i]);
        if (article.id == article_id) {
          article.like = likeCount;
          await redis.lSet("articlesList", i, JSON.stringify(article));
        }
      }
    });
  res.send({
    code: 200,
    message: "取消点赞成功",
    likeCount
  });
};
module.exports = userCanelLikes;
